package com.pan.kang.frame.role;


import com.pan.kang.frame.dao.IStoreProcedureQueryDao;
import com.pan.kang.frame.model.StoreProcedureResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Map;


@Component
public class StoreProcedureQueryRole implements IStoreProcedureQueryRole {

    @Autowired
    private IStoreProcedureQueryDao storeProcedureQueryDao;

    @Override
    public <VO> StoreProcedureResult<VO> findListByStoreProcedure(String procedureName, Class<VO> clazz,
                                                                  Map<String, Object> mapIn, Map<String, Object> mapOut) {
        Map<String, ?> retMap = storeProcedureQueryDao.executeProcedure(procedureName, mapIn, mapOut);
        return processResult(retMap, clazz, mapOut);
    }

    private <VO> StoreProcedureResult<VO> processResult(Map<String, ?> retMap, Class<VO> clazz, Map<String, Object> mapOut) {
        StoreProcedureResult<VO> storeProcedureResult = new StoreProcedureResult<VO>();
        try {
            VO vo = clazz.newInstance();
            storeProcedureResult.setResult(vo);
            if (!CollectionUtils.isEmpty(mapOut)) {
                mapOut.keySet().forEach(k -> {
                    String f = k;
                    if (f.contains("o_")) {
                        f = f.replace("o_", "");
                    }
                    try {
                        Field field = clazz.getDeclaredField(f);
                        field.setAccessible(true);
                        field.set(vo, retMap.get(k));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return storeProcedureResult;
    }
}
